package alipay

import (
	"encoding/json"
	"fmt"
)

//RefundResponse 退款响应参数
type RefundResponse struct {
	Response RefundResponseData `josn:"alipay_trade_refund_response"`
	Sign     string             `json:"sign"`
}

// RefundResponseData 退款响应参数内容
type RefundResponseData struct {
	Code    string `json:"code"`
	Msg     string `json:"msg"`
	SubCode string `json:"sub_code"`
	SubMsg  string `json:"sub_msg"`
}

// Refund 统一收单交易支付接口
func Refund(bizContent string) (err error) {
	res, err := trade("alipay.trade.refund", bizContent)
	var result RefundResponse
	err = json.Unmarshal(res, &result)
	if err != nil {
		err = fmt.Errorf("响应结果json解析失败:%v 响应原数据: %s", err, string(res))
		return
	}
	if result.Response.Code != "10000" {
		err = fmt.Errorf("支付失败失败:%v 响应原数据: %s", err, string(res))
	}
	return
}

//RefundQueryResponse 退款查询响应参数
type RefundQueryResponse struct {
	Response RefundQueryResponseData `josn:"alipay_trade_fastpay_refund_query_response"`
	Sign     string                  `json:"sign"`
}

// RefundQueryResponseData 退款查询响应参数内容
type RefundQueryResponseData struct {
	Code         string  `json:"code"`
	Msg          string  `json:"msg"`
	SubCode      string  `json:"sub_code"`
	SubMsg       string  `json:"sub_msg"`
	TradeNO      string  `json:"trade_no"`
	OutTradeNO   string  `json:"out_trade_no"`
	OutRequestNO string  `json:"out_request_no"`
	RefundReason string  `json:"refund_reason"`
	TotalAmount  float64 `json:"total_amount"`
	RefundAmount float64 `json:"refund_amount"`
}

// RefundQuery 统一收单交易交易退款查询接口
func RefundQuery(bizContent string) (result RefundQueryResponse, err error) {
	res, err := trade("alipay.trade.fastpay.refund.query", bizContent)
	err = json.Unmarshal(res, &result)
	if err != nil {
		err = fmt.Errorf("响应结果json解析失败:%v 响应原数据: %s", err, string(res))
		return
	}
	if result.Response.Code != "10000" {
		err = fmt.Errorf("退款查询失败:%v 响应原数据: %s", err, string(res))
	}
	return
}
